import MsgConst from "../../../Common/MsgConst";
import IController from "../../../Interface/IController";
import MessageManager from "../../../Util/MessageManager";
import NewWorkManager from "../NewWorkManager";

export interface IGateData {
    id: number,
    time: number,
}

export default class GateController extends IController {
    private static _instance: GateController = null;

    private _nSendHeartId: number = 0;
    private _nRecvHeartId: number = 0;
    private _timeHeartTask = null;

    public static get instance() {
        if (this._instance === null) {
            this._instance = new this;
        }
        return this._instance;
    }

    public onCtrlMessage(msgID: number, buf: any): void {
        // console.log("心跳控制器", msgID, buf);

        switch (msgID) {
            case MsgConst.HEART:
                buf = JSON.parse(buf) as IGateData;
                console.log("心跳回传:", buf);
                this._nRecvHeartId = buf.id;
                break;
        }
    }

    public startHeart() {
        this.stopHeart();
        this._timeHeartTask = setInterval(() => {
            if (this._nSendHeartId - this._nRecvHeartId > 3) {
                console.log("网络异常...提示断开连接重连网络~");
                NewWorkManager.instance.close();
                return;
            }
            this.sendHeartReq(this._nSendHeartId++, Date.now());
        }, 3000);
    }

    public stopHeart() {
        this._timeHeartTask && clearInterval(this._timeHeartTask);
        this._timeHeartTask = null;
    }

    private sendHeartReq(id: number, time: number) {
        const data = {
            id: id,
            time: time,
        };
        MessageManager.instance.send(MsgConst.HEART + "#" + JSON.stringify(data) + "#");
        // console.log("send:", MsgConst.HEART + "#" + JSON.stringify(data) + "#");

        // MessageManager.instance.send(MsgConst.HEART + '#' + id + '#' + time + '#');
        // console.log("send:", MsgConst.HEART + '#' + id + '#' + time);
    }
}